package com.nwu.records.controller;

import com.nwu.common.result.Result;
import com.nwu.records.domain.vo.AiMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import okhttp3.*;
import org.json.JSONObject;

import java.io.*;

@RestController
@RequestMapping("/ai")
@Api(tags = "AI话聊")
@Slf4j
@RequiredArgsConstructor
public class AIController {

    public static final String API_KEY = "YCOGfOvB75ovHMZMMSFukJNw";
    public static final String SECRET_KEY = "fcZZCoJFx54R4DQ5VaqDc5cijaKdWdaB";
    public static final String ERNIE_BOT_TURBO_INSTANT = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @ApiOperation("ai对话")
    @PostMapping("")
    public Result ai(String message) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String content = "{\"messages\":[" + AiMessage.user("你好") +
                "," + AiMessage.assistant("你好,请问有什么可以帮助") +
                "," + AiMessage.user(message) + "]}";
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res = response.body().string();
        res.replaceAll( "\"|:","").replace( "\\","").matches("result(.*?)is_truncated");
        log.info(res);
        return Result.success(res);
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }


}
